package tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author way
 * @create 2025-02-11 20:52
 */
public class _113_pathSum {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> res = new LinkedList<>();
        if (root == null) return res;

        List<Integer> path = new LinkedList<>();
        traversal(root, targetSum, path, res);
        return res;
    }

    private void traversal(TreeNode root, int targetSum, List<Integer> path, List<List<Integer>> res) {
        path.add(root.val);
        if (root.left == null && root.right == null) {
            if (targetSum == root.val) {
                res.add(new LinkedList<>(path));
            }
            return;
        }
        if (root.left != null) {
            traversal(root.left, targetSum - root.val, path, res);
            path.remove(path.size() - 1);
        }
        if (root.right != null) {
            traversal(root.right, targetSum - root.val, path, res);
            path.remove(path.size() - 1);
        }
    }
}
